/*
 * Copyright (c) 2018, dreamkaylee@foxmail.com All Rights Reserved.
 */

package com.common.beetl;

import java.io.IOException;
import java.io.Writer;

import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;
import org.beetl.core.ConsoleErrorHandler;
import org.beetl.core.Resource;
import org.beetl.core.ResourceLoader;
import org.beetl.core.exception.BeetlException;
import org.beetl.core.exception.ErrorInfo;

/**
 * beetl异常日志记录
 *
 * @author limk
 * @date 2018年3月26日 下午1:10:10
 * @version 1.0
 */
public class ReThrowConsoleErrorHandler extends ConsoleErrorHandler {

	private static Logger LOG = LogManager.getLogger(ReThrowConsoleErrorHandler.class);

	@Override
	public void processExcption(BeetlException ex, Writer writer) {
		// 控制台输出
		super.processExcption(ex, writer);
		LOG.info("enter beetl 异常处理 开始 。。。。。。。。。");
		ErrorInfo error = new ErrorInfo(ex);
		StringBuilder sb = new StringBuilder(">>").append(this.getDateTime()).append(":");
		sb.append(error.getType());
		sb.append(":");
		sb.append(error.getErrorTokenText());
		sb.append("位于");
		sb.append(error.getErrorTokenLine());
		sb.append("行资源:");
		sb.append(getResourceName(ex.resource.getId()));
		sb.append("\n");

		String content = null;
		ResourceLoader resLoader = ex.gt.getResourceLoader();
		try {
			Resource res = resLoader.getResource(ex.resource.getId());
			int[] range = this.getRange(error.getErrorTokenLine());
			content = res.getContent(range[0], range[1]);
			if (content != null) {
				String[] strs = content.split(ex.cr);
				int lineNumber = range[0];
				for (int i = 0; i < strs.length; i++) {
					sb.append(lineNumber);
					sb.append("|");
					sb.append(strs[i]);
					sb.append("\n");
					lineNumber++;
				}

			}
		} catch (IOException e) {
			LOG.error("beetl ioException :", e);
		}
		LOG.error(sb.toString());
		LOG.info("enter beetl 异常处理显示结束 。。。。。。。。。");
	}

}
